package com.test2;


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.HasDevTools;
import org.openqa.selenium.devtools.v113.network.Network;
import org.openqa.selenium.devtools.v113.network.model.Response;
import org.openqa.selenium.remote.Augmenter;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author kk
 * @Description Selenium DevTools功能演示
 */
public class SeleniumDevTools {

    public static void main(String[] args) throws InterruptedException {
        String webDriverDir = "浏览器驱动路径";
        // 加载驱动
        System.setProperty("webdriver.chrome.driver", "C:\\\\Program Files\\\\Google\\\\Chrome\\\\Application\\\\chromedriver.exe");
        // 创建驱动对象
        WebDriver driver = new ChromeDriver();

        driver = new Augmenter().augment(driver);
        DevTools devTools = ((HasDevTools) driver).getDevTools();
        devTools.createSession();
        devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));

        // 获取Request信息
//        devTools.addListener(Network.requestWillBeSent(), res -> {
//            System.out.println("RequestHeaders:" + res.getRequest().getHeaders());
//            System.out.println("RequestHeaders:" + res.getRequest().getUrl());
//        });

        // 获取Response信息
//        devTools.addListener(Network.responseReceived(), res -> {
//            System.out.println("ResponseHeaders:" + res.getResponse().getHeaders());
//            System.out.println("ResponseURL:" + res.getResponse().getUrl());
//        });
        driver.get("https://www.baidu.com/");

        // 获取Response响应内容
        devTools.addListener(Network.responseReceived(), res -> {
            Response response = res.getResponse();
            String url = response.getUrl();
            System.out.println("url:" + url+"响应时间："+ res.getResponse().getTiming().get().getReceiveHeadersEnd());
            // 获取network 请求的responseBody
            //String responseBody = devTools.send(Network.getResponseBody(res.getRequestId())).getBody();
        });
        driver.get("https://www.baidu.com/");

        TimeUnit.MILLISECONDS.sleep(450000);
    }
}
